import json
import sys
import urllib
import time
import os
from tencentcloud.common import credential
from tencentcloud.common.profile.client_profile import ClientProfile
from tencentcloud.common.profile.http_profile import HttpProfile
from tencentcloud.common.exception.tencent_cloud_sdk_exception import TencentCloudSDKException
from tencentcloud.tts.v20190823 import tts_client, models
import ssl
import hashlib

ssl._create_default_https_context = ssl._create_unverified_context
from config import *

class TencentcloudTTs:

    def __init__(self):
        self.SecretId = 'AKIDpTu6IR**********'
        self.SecretKey = 'pW1JTdjf***********'


    def voice_tts(self, soundtxt, outmp3file):
        self.outmp3file = outmp3file
        # _url = 'https://tts-async-audio-gz-1300466766.cos.ap-guangzhou.myqcloud.com/20220821%2F1312169624%2Fgz-7f7b24bd-0ea8-4058-9697-074ab5fbc62d.mp3?q-sign-algorithm=sha1&q-ak=AKIDJXcaKs2w4vZw5zTCrHRM7dOwre9Xk9MJ&q-sign-time=1661060655%3B1661665455&q-key-time=1661060655%3B1661665455&q-header-list=host&q-url-param-list=&q-signature=5bb7776a488ca577c256448f79137c85776b3854'
        # self.download(_url)
        # return

        try:
            # 实例化一个认证对象，入参需要传入腾讯云账户secretId，secretKey,此处还需注意密钥对的保密
            # 密钥可前往https://console.cloud.tencent.com/cam/capi网站进行获取
            cred = credential.Credential(self.SecretId, self.SecretKey)
            # 实例化一个http选项，可选的，没有特殊需求可以跳过
            httpProfile = HttpProfile()
            httpProfile.endpoint = "tts.tencentcloudapi.com"

            # 实例化一个client选项，可选的，没有特殊需求可以跳过
            clientProfile = ClientProfile()
            clientProfile.httpProfile = httpProfile
            # 实例化要请求产品的client对象,clientProfile是可选的
            client = tts_client.TtsClient(cred, "", clientProfile)

            # 实例化一个请求对象,每个接口都会对应一个request对象
            req = models.CreateTtsTaskRequest()
            params = {
                "Text": soundtxt,
                "ModelType": 1
            }

            req.from_json_string(json.dumps(params))

            # 返回的resp是一个CreateTtsTaskResponse的实例，与请求对象对应
            resp = client.CreateTtsTask(req)
            # 输出json格式的字符串回包
            # print(resp.to_json_string())
            print(resp.Data.TaskId)
            i=0
            while i<100:
                retData = self.getTaskUrl(resp.Data.TaskId)
                if (retData.StatusStr=='success' and  retData.ResultUrl!=''):
                    self.download(retData.ResultUrl)
                    break
                else:
                    time.sleep(1)
                    i= i+1
                    self.getTaskUrl(resp.Data.TaskId)


        except TencentCloudSDKException as err:
            print(err)


    def getTaskUrl(self,task_id):
        try:
            # 实例化一个认证对象，入参需要传入腾讯云账户secretId，secretKey,此处还需注意密钥对的保密
            # 密钥可前往https://console.cloud.tencent.com/cam/capi网站进行获取
            cred = credential.Credential(self.SecretId, self.SecretKey)
            # 实例化一个http选项，可选的，没有特殊需求可以跳过
            httpProfile = HttpProfile()
            httpProfile.endpoint = "tts.tencentcloudapi.com"

            # 实例化一个client选项，可选的，没有特殊需求可以跳过
            clientProfile = ClientProfile()
            clientProfile.httpProfile = httpProfile
            # 实例化要请求产品的client对象,clientProfile是可选的
            client = tts_client.TtsClient(cred, "", clientProfile)

            # 实例化一个请求对象,每个接口都会对应一个request对象
            req = models.DescribeTtsTaskStatusRequest()
            params = {
                "TaskId": task_id
            }
            # print("params==")
            # print(params)
            req.from_json_string(json.dumps(params))

            # 返回的resp是一个DescribeTtsTaskStatusResponse的实例，与请求对象对应
            resp = client.DescribeTtsTaskStatus(req)
            # 输出json格式的字符串回包
            # print(resp.to_json_string())
            return resp.Data

        except TencentCloudSDKException as err:
            print(err)

    def download(self,file_url):
        # global python_tmp, uploads_dir
        _path = os.path.abspath(".")

        # header = {"Authorization": "Bearer " + api_token}  # 设置http header
        request = urllib.request.Request(file_url)
        # try:
        _response = urllib.request.urlopen(request)

        m = hashlib.md5()
        m.update(file_url.encode('utf-8'))

        # file_name = 'readtxt_'.m.hexdigest()+".mp3"
        # filepath = _path+"/../runtime/python/"+file_name
        filepath = self.outmp3file
        if (_response.getcode() == 200):
            with open(filepath, "wb") as f:
                f.write(_response.read())  # 将内容写入图片
